import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '密码管理器',
      debugShowCheckedModeBanner: false,
      home: const Home(),
    );
  }
}

/* ---------- 数据模型 ---------- */
class Account {
  final String app;
  final String user;
  final String pwd;
  Account({required this.app, required this.user, required this.pwd});
}

/* ---------- 全局状态 ---------- */
class PasswordStore extends ChangeNotifier {
  final Map<String, List<Account>> _accounts = {
    '微信': [Account(app: '微信', user: 'xiaoming', pwd: '123456')],
    '淘宝': [Account(app: '淘宝', user: 'shop123', pwd: 'tb8888')],
  };

  Map<String, List<Account>> get accounts => _accounts;

  void add(String app, String user, String pwd) {
    _accounts.putIfAbsent(app, () => []);
    _accounts[app]!.add(Account(app: app, user: user, pwd: pwd));
    notifyListeners();
  }

  void remove(String app, int index) {
    _accounts[app]!.removeAt(index);
    if (_accounts[app]!.isEmpty) _accounts.remove(app);
    notifyListeners();
  }
}

/* ---------- Provider 小工具 ---------- */
class ChangeNotifierProvider extends InheritedWidget {
  final PasswordStore store;
  const ChangeNotifierProvider({
    Key? key,
    required this.store,
    required Widget child,
  }) : super(key: key, child: child);

  static PasswordStore of(BuildContext context) =>
      context.dependOnInheritedWidgetOfExactType<ChangeNotifierProvider>()!.store;

  @override
  bool updateShouldNotify(ChangeNotifierProvider old) => true;
}

/* ---------- 主页面 ---------- */
class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final PasswordStore store = PasswordStore();
  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    final pages = [
      const AccountList(), // 0
      AddPage(store: store), // 1
      DeletePage(store: store), // 2
    ];

    return ChangeNotifierProvider(
      store: store,
      child: Scaffold(
        appBar: AppBar(title: const Text('密码管理器')),
        body: pages[currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: currentIndex,
          onTap: (i) => setState(() => currentIndex = i),
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.list), label: '账号'),
            BottomNavigationBarItem(icon: Icon(Icons.add), label: '添加'),
            BottomNavigationBarItem(icon: Icon(Icons.delete), label: '删除'),
          ],
        ),
      ),
    );
  }
}

/* ---------- 第 1 页：账号列表 ---------- */
class AccountList extends StatelessWidget {
  const AccountList({super.key});

  @override
  Widget build(BuildContext context) {
    final store = ChangeNotifierProvider.of(context);
    return store.accounts.isEmpty
        ? const Center(child: Text('暂无账号，请去添加'))
        : ListView(
      children: store.accounts.entries.map((entry) {
        final app = entry.key;
        final accounts = entry.value;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
              child: Text(app,
                  style: const TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 18)),
            ),
            ...accounts.map(
                  (acc) => ListTile(
                title: Text(acc.user),
                subtitle: Text(acc.pwd),
              ),
            ),
            const Divider()
          ],
        );
      }).toList(),
    );
  }
}

/* ---------- 第 2 页：添加 ---------- */
class AddPage extends StatelessWidget {
  final PasswordStore store;
  const AddPage({super.key, required this.store});

  @override
  Widget build(BuildContext context) {
    final appCtrl = TextEditingController();
    final userCtrl = TextEditingController();
    final pwdCtrl = TextEditingController();

    return Scaffold(
      appBar: AppBar(title: const Text('添加账号')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(controller: appCtrl, decoration: const InputDecoration(labelText: '应用')),
            TextField(controller: userCtrl, decoration: const InputDecoration(labelText: '用户名')),
            TextField(controller: pwdCtrl, decoration: const InputDecoration(labelText: '密码')),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                if (appCtrl.text.isEmpty || userCtrl.text.isEmpty || pwdCtrl.text.isEmpty) return;
                store.add(appCtrl.text, userCtrl.text, pwdCtrl.text);
                appCtrl.clear();
                userCtrl.clear();
                pwdCtrl.clear();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('已添加')),
                );
              },
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }
}

/* ---------- 第 3 页：删除 ---------- */
class DeletePage extends StatefulWidget {
  final PasswordStore store;
  const DeletePage({super.key, required this.store});

  @override
  State<DeletePage> createState() => _DeletePageState();
}

class _DeletePageState extends State<DeletePage> {
  String? selectedApp;
  int? selectedIndex;

  @override
  Widget build(BuildContext context) {
    final apps = widget.store.accounts.keys.toList();
    return Scaffold(
      appBar: AppBar(title: const Text('删除账号')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 选应用
            DropdownButton<String>(
              isExpanded: true,
              hint: const Text('选择应用'),
              value: selectedApp,
              items: apps.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(),
              onChanged: (val) {
                setState(() {
                  selectedApp = val;
                  selectedIndex = null;
                });
              },
            ),
            const SizedBox(height: 12),
            // 选账号
            if (selectedApp != null) ...[
              DropdownButton<int>(
                isExpanded: true,
                hint: const Text('选择账号'),
                value: selectedIndex,
                items: widget.store.accounts[selectedApp]!
                    .asMap()
                    .entries
                    .map((e) => DropdownMenuItem(
                  value: e.key,
                  child: Text('${e.value.user} (${e.value.pwd})'),
                ))
                    .toList(),
                onChanged: (val) => setState(() => selectedIndex = val),
              ),
            ],
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: (selectedApp == null || selectedIndex == null)
                  ? null
                  : () {
                widget.store.remove(selectedApp!, selectedIndex!);
                setState(() {
                  selectedApp = null;
                  selectedIndex = null;
                });
                ScaffoldMessenger.of(context)
                    .showSnackBar(const SnackBar(content: Text('已删除')));
              },
              child: const Text('删除'),
            ),
          ],
        ),
      ),
    );
  }
}